import {
  Component,
  OnInit,
  OnDestroy,
  HostBinding,
  HostListener,
  Host,
  Optional,
} from '@angular/core';
import { Subject } from 'rxjs';

import { CascadeComponent } from './cascade.component';

@Component({
  selector: 'fui-cascade-item',
  template: '<ng-content></ng-content>',
})
export class CascadeItemComponent implements OnInit, OnDestroy {
  @HostBinding('class.fui-cascade-item') hostClass = true;
  @HostBinding('class.fui-cascade-item-trigger')
  get triggerClass() {
    return this.triggersSubCascade;
  }

  hovered: Subject<CascadeItemComponent> = new Subject<CascadeItemComponent>();

  /** Whether the cascade item acts as a trigger for a sub-cascade. */
  triggersSubCascade = false;

  @HostListener('click') onClick() {
    this.cascade.clickCascade(this.triggersSubCascade);
  }

  @HostListener('mouseenter') onHostHover() {
    this.handleHover();
  }

  constructor(
    /** the parent component. */
    @Optional() @Host() public cascade: CascadeComponent,
  ) {
    if (this.cascade) {
      this.cascade.addItem(this);
    }
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    if (this.cascade) {
      this.cascade.removeItem(this);
    }

    this.hovered.complete();
  }

  handleHover() {
    this.hovered.next(this);
  }
}
